﻿using Autofac; 
using Mapster;
using MapsterMapper;
using System.Reflection;
using System.Runtime.Loader;
using Yz.Core.Base;
using Yz.DataAccess.ModelMapper;
using Yz.DB.EFCore.Dal;

namespace Yz.Web.Modules
{
    public class AutofacModule : Autofac.Module
    {
        protected override void Load(ContainerBuilder containerBuilder)
        {
            #region 实现接口IDependency 的自动注入
            var baseType = typeof(IDependency);
            containerBuilder.RegisterAssemblyTypes(AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName("Yz.DataAccess")))
                  .Where(t => baseType.IsAssignableFrom(t) && t != baseType)
                  .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).AsImplementedInterfaces().InstancePerLifetimeScope();

            containerBuilder.RegisterGeneric(typeof(DbAccess<>)).As(typeof(IDbAccess<>)).PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).AsImplementedInterfaces().InstancePerLifetimeScope();
            #endregion

            #region Mapster注入
            containerBuilder.Register(ctx =>
            {
                var config = new TypeAdapterConfig();

                // 扫描程序集并应用所有 IRegister 实现
                //config.Scan(Assembly.GetExecutingAssembly());

                // 或者手动应用特定配置
                new SourceProfileApi().Register(config);
                new SourceProfileVm().Register(config);

                return config;
            }).PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).InstancePerLifetimeScope();

            containerBuilder.RegisterType<Mapper>()
                    .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).As<IMapper>()
                    .InstancePerLifetimeScope();
            #endregion


        }
    }
}
